from flask import *
import sqlite3

app = Flask(__name__)

@app.route('/fetch/<doc>')
def fetch(doc):
  db = sqlite3.connect("stypi2020.sqlite")
  c = db.cursor()
  c.execute("select post from messages where doc = ?", [doc])
  html = ""
  for row in c.fetchall():
    post = row[0]
    html += '<div class="message">%s</div>' % post
  return html

@app.route("/<doc>", methods=['GET', 'POST'])
def main(doc):
  db = sqlite3.connect("stypi2020.sqlite")

  if request.method == 'GET':
    return render_template('welcome.html', flash = '', doc=doc)

  if request.method == 'POST':
    post = request.form.get('post')
    c = db.cursor()
    c.execute("select count(*) from messages")
    if c.fetchone()[0] > 100:
      c.execute("delete from messages")

    c.execute("insert into messages values (?,?)", [doc, post])
    db.commit()
    return render_template('welcome.html', flash = "You post has been saved", doc=doc)

  db.close()


if __name__ == '__main__':
  app.run('0.0.0.0', port=8000, debug=1)
